package com.mock.ems.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.mock.base.util.BeanUtil;
import com.mock.base.util.CollectionUtil;
import com.mock.base.util.StringUtil;
import com.mock.ems.bean.SystemTip;
import com.mock.ems.common.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * Created by lichengming on 2017/6/14.
 */
public class TipController extends Controller {

    private static final Logger logger = LoggerFactory.getLogger(TipController.class);

    public void index() {
        renderJsp("/page/tip/tip_list.jsp");
    }

    public void pagination() {

        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");

        StringBuilder exceptSelectSQL = new StringBuilder(" from system_tip where 1 = 1 ");
        List<Object> params = new ArrayList<Object>();

        String code = getPara("code");
        if (StringUtil.isNotEmpty(code)) {
            exceptSelectSQL.append(" and code = ?");
            params.add(code.trim());
        }

        String tip = getPara("tip");
        if (StringUtil.isNotEmpty(tip)) {
            exceptSelectSQL.append(" and tip like ? ");
            params.add("%" + tip.trim() + "%");
        }

        Page<Record> recordList = null;
        if (params.size() == 0) {
            recordList = Db.paginate(pageNumber, pageSize, "select * ", exceptSelectSQL.toString());
        }else {
            recordList = Db.paginate(pageNumber, pageSize, "select * ", exceptSelectSQL.toString(),params.toArray());
        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", recordList.getTotalRow());
        returnMap.put("rows", recordList.getList());
        renderJson(returnMap);
    }

    public void edit() {
        Record record = Db.findById("system_tip", getPara("tipId"));
        if (null != record) {
            setAttr("tip", record.getColumns());
        }
        renderJsp("/page/tip/tip_add.jsp");
    }

    @Before(Tx.class)
    public void save() {

        SystemTip systemTip = getBean(SystemTip.class,"");
        JsonResult result = new JsonResult();
        Record record = new Record();
        try {
            record.setColumns(BeanUtil.objectToMap(systemTip));
        } catch (Exception e) {
            renderJson(result.status("-1").show("保存失败"));
            return;
        }

        boolean success;
        if (systemTip.getId() == null) {
            if (isTipExist(systemTip.getCode())) {
                renderJson(result.status("-2").show("编码已存在，请重新填写"));
                return;
            }
            success = Db.save("system_tip",record);
        }else {
            success = Db.update("system_tip",record);
        }

        if (success) {
            renderJson(result.status("000").show("保存成功"));
        }else {
            renderJson(result.status("-3").show("保存失败"));
        }
    }

    @Before(Tx.class)
    public void delete() {

        String tipIdList = getPara("tipIdList");
        JsonResult result = new JsonResult();
        if (StringUtil.isEmpty(tipIdList)) {
            renderJson(result.status("001").show("删除失败"));
            return;
        }

        StringBuilder deleteSQL = new StringBuilder("delete from system_tip where id in (");
        Object [] tips = new Object[tipIdList.split(",").length];
        int index = 0;
        for (String id : tipIdList.split(",")) {
            deleteSQL.append("?,");
            tips[index]= id;
            index ++;
        }
        deleteSQL.deleteCharAt(deleteSQL.length() - 1).append(")");


        boolean deleteResult = Db.update(deleteSQL.toString(),tips) == tips.length;
        renderJson(deleteResult ? result.status("000").show("删除成功"):result.status("002").show("删除失败"));
    }

    private boolean isTipExist(String code) {
        String sql = "select id from system_tip where code = ? ";
        return Db.findFirst(sql,code) != null;
    }

    public void isTipExist() {
        String sql = "select id from system_tip where code = ? ";
        String loginAccount = getPara("code");
        Record record = Db.findFirst(sql,loginAccount);
        renderJson(record == null ? true:false);
    }

    @Before(Tx.class)
    public void init() {

        //删除重复数据
        String sql0 = "select cu_id from zc_customer where cu_phone in (\n" +
                "\n" +
                "\t\tselect phonenum from (\n" +
                "\t\tselect cu_phone as phonenum,count(cu_phone) as c_phone from zc_customer GROUP BY cu_phone)p\n" +
                "\t\twhere c_phone > 1\n" +
                "\t)";
        List<Integer> dupliRecordList = Db.query(sql0);

        String filerIdSql = "select cu_id from (\n" +
                "\tselect * from zc_customer where cu_phone in (\n" +
                "\n" +
                "\t\tselect phonenum from (\n" +
                "\t\tselect cu_phone as phonenum,count(cu_phone) as c_phone from zc_customer GROUP BY cu_phone)p\n" +
                "\t\twhere c_phone > 1\n" +
                "\t)\n" +
                ")pp group by cu_phone";


        List<Integer> filterIdList = Db.query(filerIdSql);
        dupliRecordList.removeAll(filterIdList);

        String filerSql = "select sum(cu_profit) as total_profit,sum(cu_integral) as total_integral,cu_id from (\n" +
                "\tselect * from zc_customer where cu_phone in (\n" +
                "\n" +
                "\t\tselect phonenum from (\n" +
                "\t\tselect cu_phone as phonenum,count(cu_phone) as c_phone from zc_customer GROUP BY cu_phone)p\n" +
                "\t\twhere c_phone > 1\n" +
                "\t)\n" +
                ")pp group by cu_phone";
        List<Record> filterRecordList = Db.find(filerSql);
        if (CollectionUtil.isNotEmpty(filterRecordList)) {
            filterRecordList.forEach(item -> {
                Record itemRecord = Db.findById("zc_customer","cu_id",item.getInt("cu_id"));
                itemRecord.set("cu_profit",item.get("total_profit"))
                        .set("cu_integral",item.get("total_integral"));
                if (Db.update("zc_customer","cu_id",itemRecord)) {
                    logger.info("成功：itemRecord:{}",itemRecord.getColumns());
                }
            });
        }

        for (Integer id : dupliRecordList) {
            if (Db.deleteById("zc_customer","cu_id",id)) {
                logger.info("删除成功,id:{}",id);
            }
        }

        logger.info("全部成功");
        renderJson(new JsonResult().status("000").show("全部更新成功"));
    }


    @Before(Tx.class)
    public void init2() {

        List<Record> friendTopList = Db.find("select cu_id,ft_count from zc_friend_top where ft_count > 0 ");
        if (CollectionUtil.isNotEmpty(friendTopList)) {
            friendTopList.forEach(friendTop -> {
                int cu_id = friendTop.getInt("cu_id");
                Record userRecord = Db.findById("user",cu_id);
                if (null != userRecord) {
                    userRecord.set("invite_count",friendTop.getInt("ft_count"));
                    if (Db.update("user",userRecord)) {
                        logger.info("更新invite_count成功");
                    }
                }else {
                    logger.error("用户id:{}更新invite_count失败",cu_id);
                }
            });
        }

        //更新提现账号
        List<Record> accoutRecordList = Db.find("select * from zc_withdraw_account where wa_delete = '2'");
        if (CollectionUtil.isEmpty(accoutRecordList)) {
            renderJson(new JsonResult().status("-1").show("accoutRecordList is NULL"));
            return;
        }

        for (Record oldAccount : accoutRecordList) {
            Record userAccountRecord = Db.findFirst("select * from user_account where user_id = ? ",
                    oldAccount.getInt("cu_id"));
            if (null == userAccountRecord) {
                logger.info("userAccountRecord is NULL. user_id:{}",oldAccount.getInt("cu_id"));
                continue;
            }
            if (null != userAccountRecord) {
                userAccountRecord.set("alipay_account",oldAccount.get("wa_account"));
            }
            if (Db.update("user_account",userAccountRecord)) {
                logger.info("更新成功");
            }
        }


        String sql00 = "select cu_id from zc_customer where cu_level_group = 1 and cu_parent_id = 0";
        List<Integer> cuIdList = Db.query(sql00);
        if (CollectionUtil.isNotEmpty(cuIdList)) {
            cuIdList.forEach(cuId-> {
                Record userRecord = Db.findById("user",cuId);
                if (null != userRecord) {
                    userRecord.set("role","1,2");
                   if (Db.update("user",userRecord)) {
                       logger.info("更新用户成功,用户id:{}",cuId);
                   }
                }else {
                    logger.info("======cuId:{}==========",cuId);
                }
            });
        }


        List<Record> canvassList = Db.find("select c_money,cu_acc from zc_canvass where c_money > 0");
        if (CollectionUtil.isNotEmpty(canvassList)) {
            canvassList.forEach(item -> {
                String cu_acc = item.getStr("cu_acc");
                if (StringUtil.isNotEmpty(cu_acc)) {
                    Record cu_record = Db.findFirst("select cu_id,cu_level_group from zc_customer where cu_acc = ? ",cu_acc);
                    if (null != cu_record) {


                        int cu_level_group = 0;

                        try {
                            cu_level_group = cu_record.getInt("cu_level_group");
                        }catch (Exception e) {
                            logger.info("XXXX:{}",new Object[]{cu_record.get("cu_level_group")});
                        }

                        if (cu_level_group == 0) return;

                        String tableName = "cooperation_service_center";
                        if (cu_level_group == 3) {
                            tableName = "cooperation_partner";
                        }else if (cu_level_group == 5) {
                            tableName = "area_agent";
                        }

                        Record record0 =
                                Db.findFirst("select * from " + tableName + " where user_id = ? ",cu_record.getInt("cu_id"));
                        if (null != record0) {
                            record0.set("pay_amount",item.getDouble("c_money"));
                            if (Db.update(tableName,record0)) {
                                logger.info("更新：{} money成功",tableName);
                            }
                        }
                    }
                }else {
                    logger.info("au_acc is null");
                }
            });
        }

        List<Record> partnerList = Db.find("select * from cooperation_partner");
        if (CollectionUtil.isNotEmpty(partnerList)) {
            partnerList.forEach(partner -> {
                Integer addTime = 0;
                try {
                    addTime = Db.queryInt("select c_add_time from zc_canvass where cu_mobile = ? limit 1",partner.get("phone"));
                }catch (Exception e) {
                    logger.error("partner=======:{}",new Object[]{partner.get("phone")});
                }

                if (addTime == 0) {
                    logger.error("serviceCenter : addTime is 0");
                    return;
                }

                if (null != addTime) {
                    partner.set("create_time",new Date(addTime * 1000));
                    if (Db.update("cooperation_partner",partner)) {
                        logger.info("更新cooperation_partner成功。id:{}",partner.getLong("id"));
                    }
                }
            });
        }

        List<Record> serviceCenterList = Db.find("select * from cooperation_service_center");
        if (CollectionUtil.isNotEmpty(serviceCenterList)) {
            serviceCenterList.forEach(serviceCenter -> {
                Integer addTime = 0;
                try {
                    addTime = Db.queryInt("select c_add_time from zc_canvass where cu_mobile = ? limit 1",serviceCenter.get("phone"));
                }catch (Exception e) {
                    logger.error("partner=======:{}",new Object[]{serviceCenter.get("phone")});
                }

                if (addTime == 0) {
                    logger.error("serviceCenter : addTime is 0");
                    return;
                }
                if (null != addTime) {
                    serviceCenter.set("create_time",new Date(addTime * 1000));
                    if (Db.update("cooperation_service_center",serviceCenter)) {
                        logger.info("更新cooperation_service_center。id:{}",serviceCenter.getLong("id"));
                    }
                }
            });
        }

        List<Record> areaAgentList = Db.find("select * from area_agent");
        if (CollectionUtil.isNotEmpty(areaAgentList)) {
            areaAgentList.forEach(areaAgent -> {
                Integer addTime = 0;
                try {
                    addTime = Db.queryInt("select c_add_time from zc_canvass where cu_mobile = ? limit 1",areaAgent.get("phone"));
                }catch (Exception e) {
                    logger.error("partner=======:{}",new Object[]{areaAgent.get("phone")});
                }

                if (addTime == 0) {
                    logger.error("area agent : addTime is 0");
                    return;
                }
                if (null != addTime) {
                    areaAgent.set("create_time",new Date(addTime * 1000));
                    if (Db.update("area_agent",areaAgent)) {
                        logger.info("更新area_agent。id:{}",areaAgent.getLong("id"));
                    }
                }
            });
        }

        renderJson(new JsonResult().status("000").show("全部更新成功"));
    }

}
